<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Three.js Add Label and Click Event Example</title>
    <style>
        body { margin: 0; }
        canvas { display: block; }
    </style>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
<script>
    let scene, camera, renderer;

    init();
    animate();

    function init() {
        scene = new THREE.Scene();
        camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        renderer = new THREE.WebGLRenderer();

        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);

        // 创建一个立方体对象作为模型
        let geometry = new THREE.BoxGeometry();
        let material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
        let cube = new THREE.Mesh(geometry, material);
        cube.position.set(0, 0, 0);
        scene.add(cube);

        // 创建标签
        let labelCanvas = document.createElement('canvas');
        let ctx = labelCanvas.getContext('2d');
        labelCanvas.width = 200;
        labelCanvas.height = 50;
        ctx.font = '20px Arial';
        ctx.fillStyle = 'white';
        ctx.fillText('Hello, Label!', 10, 30);

        let texture = new THREE.CanvasTexture(labelCanvas);
        let spriteMaterial = new THREE.SpriteMaterial({ map: texture });
        let sprite = new THREE.Sprite(spriteMaterial);
        sprite.position.set(0, 1, 0); // 标签位置与模型位置相对
        sprite.scale.set(2, 0.5, 1);
        scene.add(sprite);

        camera.position.z = 5;

        // 监听标签的点击事件
        sprite.onClick = () => {
            alert('You clicked the label!');
        };

        renderer.domElement.addEventListener('click', event => {
            let mouse = new THREE.Vector2(
                (event.clientX / window.innerWidth) * 2 - 1,
                -(event.clientY / window.innerHeight) * 2 + 1
            );

            let raycaster = new THREE.Raycaster();
            raycaster.setFromCamera(mouse, camera);
            let intersects = raycaster.intersectObjects([sprite]);

            if (intersects.length > 0) {
                sprite.onClick(); // 触发点击事件
            }
        });
    }

    function animate() {
        requestAnimationFrame(animate);
        renderer.render(scene, camera);
    }
</script>
</body>
</html>
